<template>
  <!-- 歌曲列表i -->
  <div class="sing-list-container">
    <!-- title -->
    <div class="list-title">
      <div>操作</div>
      <div>音乐标题</div>
      <div>歌手</div>
      <div>专辑</div>
      <div>时长</div>
      <div>热度</div>
    </div>
    <div class="list-container">
      <div
        class="container-box"
        v-for="(item, index) in searchData.searchData.result.songs"
        :class="setClassByIsPlay(item)"
        :key="index"
        @dblclick="setMusicSrc(item.noCopyrightRcmd, item.id, item.fee)"
      >
        <!-- 如果数据存在 -->
        <template v-if="item">
          <div class="list-sing-on">
            <!-- 序号 -->
            <template v-if="searchData.orderIndex">
              <span>{{
                serialStandard(searchData.orderIndex + (index + 1))
              }}</span>
            </template>
            <!-- 如果是分页传来的数据 就不用更改序号 -->
            <span v-else>{{ serialStandard(index + 1) }}</span>
            <span class="muisc-operation">
              <!-- 取消收藏 -->
              <i
                @click="addMyLove(item.id, 'false')"
                v-if="userLoveList.indexOf(item.id, 0) != -1"
                ><van-icon name="like" color="#ec4141"
              /></i>
              <!-- 添加收藏 -->
              <i @click="addMyLove(item.id, 'true')" v-else
                ><van-icon name="like-o"
              /></i>
              <!-- 下载 -->
              <i @click="getMusicDownload(item.id)"
                ><van-icon name="back-top"
              /></i>
            </span>
          </div>
          <!-- 歌名 -->
          <div class="list-sing-name">
            <span
              v-html="highKey(item.name)"
              :style="item.noCopyrightRcmd == null ? '' : 'color:#cfcfcf'"
            ></span>
            <!-- 歌名描述 -->
            <span
              class="music-name-describe"
              v-show="item.alia.length > 0"
              :style="item.noCopyrightRcmd == null ? '' : 'color:#cfcfcf'"
              >（{{ item.alia[0] }}）</span
            >
            <!-- 歌曲附带小插件 -->
            <ul class="music-additional" v-if="item.noCopyrightRcmd == null">
              <!-- sq -->
              <li class="music-sq" v-show="item.sq != null">SQ</li>
              <!-- mv -->
              <li v-show="item.mv != 0">MV</li>
              <!-- vip -->
              <li class="muisc-vip" v-show="item.fee == 1">VIP</li>
              <!-- 试听 -->
              <li v-show="item.fee == 1">试听</li>
            </ul>
          </div>
          <!-- 歌手名 -->
          <div class="list-sing-user-name">
            <span v-html="highKey(item.ar[0].name)"> </span>
            <span v-if="item.ar[1]"> / </span>
            <span v-if="item.ar[1]" v-html="highKey(item.ar[1].name)"></span>
          </div>
          <!-- 专辑 -->
          <div class="list-album-name">
            <span v-html="highKey(item.al.name)"></span>
          </div>
          <div class="list-sing-time">
            {{ formatDate(new Date(item.dt), "mm:ss") }}
          </div>
          <div class="list-sing-pop">
            <van-progress
              inactive
              :percentage="item.pop"
              :stroke-width="0"
              :show-pivot="false"
              class="sing-progress"
            />
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";
import { Dialog, Toast } from "vant";
import { formatDate } from "../../hook/formatTime";

const store = useStore();
const router = useRouter();
const route = useRoute();

// 登录凭据
const cookie = store.state.m_user.cookie;

// 时间戳
const nowTime = new Date().getTime();

// 接收传递来的数据
const searchData = defineProps(["searchData", "orderIndex"]);
// 搜索关键词
const searchTitle = store.state.m_search.searchTitle;

const userLoveList = ref("");

// 选中歌曲id
const musicId = computed(() => {
  return store.state.musicSrc;
});

// 根据是否播放来设置不同的类名
const setClassByIsPlay = (item) => {
  // 此处传递 item 是为了兼容排行榜页面
  if (route.path == "/findMusic/rankingList") return "container-box";
  if (store.state.isPlay == false)
    return item.id == musicId.value
      ? "container-box double-active-bofang"
      : "container-box";
  return item.id == musicId.value
    ? "container-box double-active-zanting"
    : "container-box";
};

// 获取用户喜欢列表
const getUserLoveList = () => {
  axios
    .post(
      `/likelist?uid=${store.state.m_user.userInfo.userId}&cookie=${cookie}&timestamp=${nowTime}`
    )
    .then((res) => {
      userLoveList.value = res.data.ids;
      store.commit("m_user/updateUserLoveList", res.data.ids);
    })
    .catch((err) => {
      console.error(err);
    });
};
getUserLoveList();

// 获取歌曲链接
const setMusicSrc = async (isCopyrightRcmd, id, fee) => {
  // 试听
  if (fee == 1) return Toast("无 VIP 试听都不给 ！！");
  // 可以听
  if (isCopyrightRcmd == null) return store.commit("updateMusicSrc", id);
  // 无版权
  return Dialog.alert({
    title: "当前歌曲暂无音源",
    message: "因版权方要求，该资源暂时无法播放，我们正在争取歌曲回归",
    theme: "round-button",
    confirmButtonText: "知道了",
    confirmButtonColor: "#ec4141",
    width: "460",
  });
};

// 高亮关键词
const highKey = (text) => {
  // 非搜索页返回原值 避免污染歌单页
  if (route.path != "/search-info-list/search-single") return text;
  return text.replace(
    searchTitle,
    `<strong style='color: #4376b1;font-weight: 500;'>${searchTitle}</strong>`
  );
};

// 序号标准化
const serialStandard = (index) => {
  if (index <= 9) return `0${index}`;
  return index;
};

// 收藏音乐
const addMyLove = (id, flag) => {
  axios
    .post(`/like?id=${id}&like=${flag}&cookie=${cookie}&timestamp=${nowTime}`)
    .then((res) => {
      getUserLoveList();
      console.log(res);
      if (!res) return Toast("服务器错误");
      if (flag == "false") {
        Toast("取消喜欢成功 ~");
      } else {
        Toast("已添加到我喜欢的音乐 ~ ");
      }
      // 刷新空白路由更新数据
      router.push({
        name: "refresh",
      });
    })
    .catch((err) => {
      console.error(err);
    });
};

// 获取音乐下载链接(暂时未实现)
const getMusicDownload = (id) => {
  axios
    .get(`/song/download/url?id=${id}`)
    .then((res) => {
      Toast("已开始获取歌曲下载链接 如果没有开始下载 那说明没有下载");
    })
    .catch((err) => {
      console.error(err);
    });
};
</script>
<style lang='less'>
@import url(../../assets/fonts/player/iconfont.css);

.sing-list-container {
  width: 100%;
  font-size: 13px;
  margin-bottom: 100px;
  color: #888888;

  .list-title,
  .container-box {
    display: flex;
    // 双击取消选中
    user-select: none;

    &:hover {
      cursor: default;
    }

    div {
      padding: 5px 0;
    }

    div:nth-child(1) {
      display: flex;
      flex: 0.05;
      padding-left: 20px;
      color: #00000042;

      .muisc-operation {
        margin-left: 10px;
        display: flex;
        width: 40px;
        justify-content: space-around;
        color: #00000073;
        font-size: 16px;

        i {
          &:hover {
            cursor: pointer;
          }

          &:nth-child(2) {
            transform: rotate(180deg);
          }
        }
      }
    }
    div:nth-child(2) {
      flex: 0.33;
      span:nth-child(1),
      span:nth-child(2) {
        max-width: 156px;
        /* 文字省略 */
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }
      .music-name-describe {
        color: #9b9b9b;
      }
    }
    div:nth-child(3) {
      flex: 0.16;
      max-width: 190px;
      /* 文字省略 */
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }
    div:nth-child(4) {
      flex: 0.24;
      padding-right: 20px;

      span {
        max-width: 300px;
        /* 文字省略 */
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }
    }
    div:nth-child(5) {
      flex: 0.09;
      color: #00000071;
    }
    div:nth-child(6) {
      flex: 0.13;
      margin-top: 5px;

      .sing-progress {
        width: 60px;
        span {
          top: 2px;
          height: 6px;
        }
      }
    }
  }

  .double-active-bofang {
    .list-sing-on {
      position: relative;

      &::before {
        display: block;
        content: "\e87c";
        font-size: 16px;
        font-family: "iconfont" !important;
        font-style: normal;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        color: #ff0000e0;
      }

      span:nth-child(1) {
        display: none;
      }
    }
    .list-sing-name {
      color: #ff0000e0 !important;
    }
  }

  .double-active-zanting {
    .list-sing-on {
      position: relative;

      &::before {
        display: block;
        content: "\e63d";
        font-size: 15px;
        font-family: "iconfont" !important;
        font-style: normal;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        color: #ff0000e0;
      }

      span:nth-child(1) {
        display: none;
      }
    }
    .list-sing-name {
      color: #ff0000e0 !important;
    }
  }

  .list-container {
    .container-box {
      &:nth-child(odd) {
        background-color: #f9f9f9;
      }
      &:hover {
        background-color: #f0f1f2;
      }

      // 表格样式
      div:nth-child(2) {
        display: flex;
        align-items: baseline;
        color: #363636;

        .music-additional {
          display: flex;
          margin-left: 6px;

          .muisc-vip {
            border: 1px solid #fe672e;
            color: #fe672e;
          }

          li {
            margin-left: 6px;
            width: 20px;
            height: 10px;
            border: 1px solid #ec4141;
            border-radius: 2px;
            color: #ff0000;
            font-size: 12px;
            line-height: 10px;
            text-align: center;
            font-family: "微软雅黑";

            &:last-child {
              font-size: 10px;
              width: 24px;
            }
          }
        }
      }
    }
  }
}
</style>